﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;



namespace client
{
    public partial class Form1 : Form
    {
        private byte[] data = new byte[1024];
        private Socket client;
       
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            btnSend.Enabled = false;
            btnConnect.Enabled = true;
            btnDisconnect.Enabled = false;
            txtText.Enabled = false;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                btnSend.Enabled = true;
                btnDisconnect.Enabled = true;
                btnConnect.Enabled = false;
                txtIPAddress.Enabled = false;
                txtPortNo.Enabled = false;
                txtText.Enabled = true;

                txtConnectStatus.Text = "Connecting to server .....";

                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                int port;
                port = int.Parse(txtPortNo.Text);
                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(txtIPAddress.Text), port);
                client.BeginConnect(remoteEP, new AsyncCallback(OnConnected), null);
            }
            catch
            {
                CloseConnection();
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            btnDisconnect.Enabled = false;
            btnSend.Enabled = false;
            btnConnect.Enabled = true;
            txtPortNo.Enabled = true;
            txtIPAddress.Enabled = true;
            txtText.Enabled = false;
            CloseConnection();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {                
                if (client == null || client.Connected == false)
                {
                    MessageBox.Show("Please connect to Server!");
                }
                else
                {
                    byte[] message = Encoding.ASCII.GetBytes(txtText.Text);
                    client.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(onDatasent), null);
                }
            }
            catch (SocketException)
            {
                CloseConnection();
            }
        }

        void OnConnected(IAsyncResult result)
        {
            try
            {
                client.EndConnect(result);
                txtConnectStatus.Text = "Connected to:  = " + client.RemoteEndPoint;
                client.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
            }
            catch
            {
                CloseConnection();
            }
        }

        void onDatasent(IAsyncResult result)
        {
            try
            {
                int sent = client.EndSend(result);
                client.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
            }
            catch (SocketException)
            {
                CloseConnection();
            }

        }

        void OnDataReceived(IAsyncResult result)
        {
            try
            {
                int receive = client.EndReceive(result);
                string message = Encoding.ASCII.GetString(data, 0, receive);
                if (String.IsNullOrEmpty(message) == false && message.Contains("\0\0\0") == false)
                {
                    lbxText.Items.Add(message);
                }
            }
            catch (Exception)
            {
                CloseConnection();
            }

        }

        public void CloseConnection()
        {
            try
            {
                client.Shutdown(SocketShutdown.Both);

                client.Disconnect(true);
                if (client.Connected)
                    Console.WriteLine("We're still connnected");
                else
                    Console.WriteLine("We're disconnected");

                txtConnectStatus.Text = "Disconnected  ...";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}

